package com.draw.cli.gui.panel.draw;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.xml.ws.WebServiceException;

import com.draw.cli.webclient.ColorClient;
import com.draw.core.Color;
import com.draw.webinterface.ColorInterface;

public class ToolboxPanel extends JPanel implements ActionListener {
	private static final long serialVersionUID = -4787429692353033646L;

	private JSpinner size;
	private ArrayList<JButton> colorBut;
	private ArrayList<Color> color;
	private int selectedColor;

	private JPanel pan;

	public ToolboxPanel() throws MalformedURLException, WebServiceException {
		this.setLayout(new FlowLayout());

		pan = new JPanel();
		pan.setLayout(new BoxLayout(pan,BoxLayout.PAGE_AXIS));

		this.size = new JSpinner(new SpinnerNumberModel(5, 1, 15, 1));
		pan.add(this.size);

		pan.add(new JLabel());
		
		ColorInterface ci = ColorClient.getInstance();
		List<Color> lc = ci.getAllColor();
		this.color = new ArrayList<Color>();
		for (Color c : lc) {
			this.color.add(c);
		}

		this.colorBut = new ArrayList<JButton>();

		for (int i = 0; i < color.size(); i++) {
			JButton b = new JButton();
			b.setPreferredSize(new Dimension(20,15));
			b.setBackground(this.color.get(i).getColor());
			b.addActionListener(this);
			this.colorBut.add(b);
			pan.add(b);
		}
		this.colorBut.get(0).setEnabled(false);
		this.selectedColor = 0;

		this.add(pan);
		this.setVisible(true);
	}

	public int getThickness() {
		return (Integer) this.size.getValue();
	}

	public Color getColor() {
		return this.color.get(selectedColor);
	}

	public void actionPerformed(ActionEvent arg0) {
		for (int i = 0; i < this.colorBut.size(); i++) {
			if (this.colorBut.get(i).equals(arg0.getSource())) {
				this.selectedColor = i;
				this.colorBut.get(i).setEnabled(false);
			} else {
				this.colorBut.get(i).setEnabled(true);
			}
		}
	}
}
